<template>
  <div>
    <div>
      <el-row>
        <el-col :span="6">
          <el-button type="primary" @click="up()">上传封面</el-button>
        </el-col>
        <el-col :span="6">
          <el-button type="success" @click="onSubmit()">保存更改</el-button>
        </el-col>
        <el-col :span="6">
          <el-button type="warning" @click="cancle()">取消更改</el-button>
        </el-col>
        <el-col :span="6">
          <el-popconfirm
            title="危险操作！销毁课程不可恢复！"
            confirm-button-text="确定"
            cancel-button-text="取消"
            @confirm="confirmEvent"
            @cancel="cancelEvent"
          >
            <template #reference>
              <el-button type="danger">销毁课程</el-button>
            </template>
          </el-popconfirm>
        </el-col>
      </el-row>
    </div>
    <div class="formContainer">
      <el-form :model="course" label-width="120px">
        <el-form-item label="课程名称">
          <el-input v-model="course.name" />
        </el-form-item>
        <el-form-item label="课程时间">
          <el-col :span="12">
            <el-date-picker
              v-model="course.start"
              type="date"
              value-formate="timestamp"
              placeholder="开始时间"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="12">
            <el-date-picker
              v-model="course.end"
              type="date"
              value-formate="timestamp"
              placeholder="结束时间"
              style="width: 100%"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="课程价格">
          <el-col :span="2">
            <el-switch v-model="isPay" />
          </el-col>
          <el-col :span="2" v-show="isPay">
            <span>价格：</span>
          </el-col>
          <el-col :span="6" v-show="isPay">
            <el-input-number
              v-model="course.price"
              :precision="2"
              :step="0.1"
              :max="10"
            />
          </el-col>
          <!-- 付费的话再添加选择价格 -->
        </el-form-item>
        <el-form-item label="课程标签">
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            class="mx-1"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="InputRef"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
          >
            + New Tag
          </el-button>
        </el-form-item>
        <el-form-item label="开课班级">
          <el-input v-model="course.openClass" />
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input v-model="course.introduction" type="textarea" />
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      v-model="dialogTableVisible"
      title="课程封面"
      center
      align-center
    >
      <el-upload
        ref="uploadDemo"
        class="upload-demo"
        drag
        :before-upload="beforUpload"
        :headers="headerObj"
        :action="targetUrl"
        :file-list="fileList"
        list-type="picture"
        :on-success="uploadSuccess"
        :on-error="uploadFail"
        :limit="1"
        :on-exceed="exceed"
        :auto-upload="false"
        accept=".jpg,.png,.JPG,.PNG"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          Drop file here or <em>click to upload</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            jpg/png files with a size less than 5M
            <el-button
              size="small"
              style="margin-left: 50px"
              @click="dialogTableVisible = false"
              >取 消</el-button
            >
            <el-button size="small" type="primary" @click="upload1"
              >确 定</el-button
            >
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>
import mitt from "@/plugins/mitt";
import { getParams } from "@/commonFunction/url";
import {
  getCourseMessage,
  updateCourseMessage,
  deleteCourseByCid,
} from "@/api/course";
import { nextTick } from "vue";
export default {
  data() {
    return {
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      dynamicTags: [],
      courseId: "",
      course: {
        cover: "",
        createTime: "",
        end: "", //课程结束时间
        id: "", //课程ID
        introduction: "", //课程简介
        name: "", //课程名称
        openClass: "", //开课班级
        price: 0,
        school: "",
        start: "",
        tags: "",
        teacher: "", //任课老师默认为创建课程的老师
      },
      isPay: false,
      inputVisible: false,
      inputValue: "",
      dialogTableVisible: false,
      fileList: [],
      url: "http://localhost:8088/api/course/uploadCourseImage",
      targetUrl: "",
    };
  },
  methods: {
    getCourse() {
      getCourseMessage(this.courseId).then((res) => {
        if (res.code == 200) {
          this.course.cover = res.data.cover;
          this.course.createTime = res.data.createTime;
          this.course.end = new Date(res.data.end);
          this.course.start = new Date(res.data.start);
          this.course.id = res.data.id;
          this.course.introduction = res.data.introduction;
          this.course.name = res.data.name;
          this.course.openClass = res.data.openClass;
          this.course.price = res.data.price;
          this.course.school = res.data.school;
          this.course.tags = res.data.tags;
          this.course.teacher = res.data.teacher;
          this.dynamicTags = [...res.data.tags.split("/")];
          this.dynamicTags.pop();
        }
      });
    },
    showInput() {
      this.inputVisible = true;
      nextTick(() => {
        this.$refs.InputRef.input.focus();
      });
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    handleInputConfirm() {
      if (this.inputValue) {
        this.dynamicTags.push(this.inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    onSubmit() {
      let temp = this.dynamicTags.join("/") + "/";
      this.course.tags = temp;
      updateCourseMessage(this.course).then((res) => {
        console.log(res);
        if (res.code == "200") {
          ElMessage({
            type: "success",
            message: "更新成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "更新失败",
          });
        }
      });
    },
    cancle() {
      let pro = new Promise((res, rej) => {
        setTimeout(() => {
          this.getCourse();
          res();
        }, 0);
      });
      pro.then((res) => {
        ElMessage({
          type: "info",
          message: "取消修改",
        });
      });
    },
    up() {
      this.dialogTableVisible = true;
    },
    //图片文件上传相关操作
    exceed() {
      ElMessage({
        type: "warning",
        message: "一次只能上传一个文件",
      });
    },
    uploadSuccess(response) {
      this.fileList = [];
      this.dialogTableVisible = false;
      //根据返回值做出对应反馈
      if (response.code == 200) {
        ElMessage({
          type: "success",
          message: "上传成功",
        });
        this.test();
      } else {
        ElMessage({
          type: "error",
          message: "上传失败",
        });
      }
    },
    uploadFail() {
      ElMessage({
        type: "error",
        message: "上传失败",
      });
      this.fileList = [];
    },
    beforUpload() {
      this.targetUrl = this.url + `?cid=${this.courseId}`;
    },
    // 对选中文件进行上传
    upload1() {
      //手动提交上传
      this.$refs.uploadDemo.submit();
    },
    confirmEvent() {
      this.deleteCourse();
      console.log("销毁课程！");
    },
    cancelEvent() {
      console.log("已取消危险操作！");
    },
    deleteCourse() {
      deleteCourseByCid(this.courseId).then((res) => {
        if (res.code == "200") {
          ElMessage({
            type: "success",
            message: "课程删除成功！",
          });
          this.$router.push({
            name: "space",
          });
        } else {
          ElMessage({
            type: "error",
            message: "课程删除失败！",
          });
        }
      });
    },
    test() {
      mitt.emit("change");
    },
  },
  created() {
    this.courseId = getParams();
    this.getCourse();
  },
  mounted() {},
  computed: {},
};
</script>
<style scoped>
.formContainer {
  width: 90%;
  margin-left: 5%;
  padding-top: 20px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>